import React from 'react'
import classNames from 'classnames'
import * as PropTypes from 'prop-types'

export default class Tabs extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            selectedIndex: props.selectedIndex
        }
    }
    static propTypes = {
        id: PropTypes.string,
        name: PropTypes.string,
        className: PropTypes.string,
        children: PropTypes.node,
        //onChanged: PropTypes.func,
        //selectedIndex: PropTypes.number
    }
    static defaultProps = {
        name: '',
        id: '',
        className: '',
        onChanged: () => { },
        selectedIndex: 0
    }
    selectTab(index) {
        if (this.state.selectedIndex !== index) {
            if (this.props.onChanged) {
                this.props.onChanged(index, this.state.selectedIndex)
            }
            this.setState({ selectedIndex: index })
        }
    }
    activeClassName(index, ...defaultClassNames) {
        return classNames(...defaultClassNames, { active: this.state.selectedIndex === index })
    }
    render() {
        let {
            className,
            children
        } = this.props;
        return (
            <div className={classNames("tabs", className)}  >
                <ul className="tab-header">
                    {children.map((item, index) => {
                        return <li key={index}
                            onClick={() => this.selectTab(index)}
                            className={this.activeClassName(index)}>{item.props.title}
                        </li>
                    })}
                </ul>
                <div className='tab-content' >
                    {children.map((item, index) => {
                        return <div key={index} className={this.activeClassName(index, 'tab')}>{item.props.children}</div>
                    })}
                </div>
            </div>
        )
    }
}

